package com.blackto.lib.eventbus;

import com.blackto.lib.eventbus.rabbitmq.RabbitMQEventBus;
import lombok.Data;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
@ConfigurationProperties("eventbus.queue")  // 用于从yml文件中读取配置属性
@Data
@ComponentScan
@ConditionalOnClass(RabbitMQEventBus.class)
public class RabbitMQEventBusConfig {

    private String name;

    @Resource
    AmqpAdmin amqpAdmin;

    // 需要先创建队列，否则构造rabbitMQEventBus时，为其中的方法添加监听时会因为找不到队列而报错
    @Bean
    public Queue queue(){
        Queue queue = new Queue(name);
        amqpAdmin.declareQueue(queue);
        return queue;
    }

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    public RabbitMQEventBus rabbitMQEventBus(IEventBusSubscriptionsManager subscriptionsManager,
                                             RabbitTemplate rabbitTemplate,
                                             AmqpAdmin amqpAdmin,
                                             ApplicationContext context){
        return new RabbitMQEventBus(name, subscriptionsManager, rabbitTemplate, amqpAdmin, context);
    }

}
